package com.baigt.j8.optional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {
        System.out.println(Optional.ofNullable("Hello").orElse("Default"));
//        Optional.of(null);
        Optional<String> hello = Optional.of("Hello");
        if (hello.isPresent()) {
            System.out.println(hello.get());
        }
        System.out.println("......");
        //推荐下边这种
        hello.ifPresent(System.out::println);
        System.out.println(Optional.ofNullable(null).orElse("Default"));
        System.out.println(Optional.ofNullable(null).orElseGet(()->"elseGet default"));
//        System.out.println(Optional.ofNullable(null).orElseThrow(()->new RuntimeException("值为空")));

        System.out.println("#########");
        List<OptionalUsed> optionalUseds = Arrays.asList(new OptionalUsed("ricky"), new OptionalUsed("hello"));
        OptionalCompose compose=new OptionalCompose();
        compose.setUseds(optionalUseds);
        Optional.ofNullable(compose).map(c->c.getUseds()).orElse(Collections.emptyList()).forEach(u->{
            System.out.println(u.getName());
        });
    }
}
class OptionalCompose{
    String name;
    List<OptionalUsed> useds;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<OptionalUsed> getUseds() {
        return useds;
    }

    public void setUseds(List<OptionalUsed> useds) {
        this.useds = useds;
    }
}
class OptionalUsed{
    String name;
    int age;

    public OptionalUsed(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
